#!/usr/bin/env python
# coding=utf-8
from cffi import FFI
from inspect import getmembers
from pprint import pprint
import json
import re
import os
import glob

ffi = FFI()
ffi.cdef(open('pffi.h').read())
lib = ffi.dlopen("../../../target/release/libpoker_ffi.dylib")

# 打开文件
non_empty_lines=[]
with open('spades_bid_test.txt', 'r') as file:
     # 遍历文件的每一行
    for line in file:
        # 使用正则表达式匹配包含数字或字母的行
        if re.search(r'[0-9a-zA-Z]', line):
            # 打印匹配的行
            non_empty_lines.append(line.strip())
# non_empty_lines = [line.strip() for line in lines if line.strip()]
# 初始化变量
data = []
current_group = []
# 每5行组成一个子数组
groups = []
current_group = []

for line in non_empty_lines:
    current_group.append(line)
    if len(current_group) == 5:
        groups.append(current_group)
        current_group = []
# 创建一个字典来映射旧值到新值
value_mapping = {'J': '11', 'Q': '12', 'K': '13', 'A': '1'}
# 打印分组后的数组
group_index = 0
result = []
for group in groups:
    group_index+=1
    hand_cards =[]
    banker =0
    current_seat_id = 0
    bids=[]
    cards_arr=[]
    print("group_index",group_index," group =",group)
    result.append(("group index = "+str(group_index)+" begin"))
    for str_g in group:
        if len(str_g) == 1:
            banker = int(str_g)
            current_seat_id = (banker+1)%4
        else:   
            parts = str_g.split('｜')
            cards_s = parts[0].strip().split('\t')
            lengths = parts[1].strip().split('\t')
             #校验牌的长度
            total = 0 
            for length in lengths:
                total += int(length)
            if total != 13:
                print("Total length =  ", total,"group index = ", group_index)
            # 只为记录原始牌 开始
            grouped_cards_s = []
            start = 0
            for length in lengths:
                count = int(length)
                group = cards_s[start:start+count]
                grouped_cards_s.append(group)
                start += count
            # print(grouped_cards_s)
            cards_arr.append(grouped_cards_s)
            # 只为记录原始牌 结束
            grouped_cards = []
            start = 0
            cards_v = [value_mapping.get(item, item) for item in cards_s]

           
            # print(cards)
            for length in lengths:
                count = int(length)
                group = cards_v[start:start+count]
                grouped_cards.append(group)
                start += count
            start = 1
            new_cards = []
            for cards in grouped_cards:
                for card in cards:
                    if start<4:
                        new_cards.append(start*13+int(card))
                    else:
                        new_cards.append(int(card))
                start +=1   
            print(new_cards)
            hand_cards.append(new_cards)
    # 构建一个示例JSON结构
    data = {
        "banker": banker,  # 更改banker的值
        "current_seat_id": current_seat_id,  # 更改current_seat_id的值
        "seats": [
            {
                "bid": -1,
                "blind_nil": 0,
                "cards": {
                    "cards": hand_cards[0],
                    "cards_len": 13
                }
            },
            {
                "bid": -1,
                "blind_nil": 0,
                "cards": {
                    "cards": hand_cards[1],
                    "cards_len": 13
                }
            },
            {
                "bid": -1,
                "blind_nil": 0,
                "cards": {
                    "cards":  hand_cards[2],
                    "cards_len": 13
                }
            },
            {
                "bid": -1,
                "blind_nil": 0,
                "cards": {
                    "cards": hand_cards[3],
                    "cards_len": 13
                }
            }
        ],
        "spades_break": 0,
        "turns": {
            "turn_plays": [],
            "turns_len": 0
        }
    }
    print(data)
    data_table = open('table.json').read()
    srn_py = ffi.new("rs_SpadesRound *", data)
    stn_py = ffi.new("rs_SpadesTable *", json.loads(data_table))
    bid = lib.rs_SpadesAi_bid(srn_py, stn_py)
    print("seat_id = ",current_seat_id," bid = ",bid )
    bids.append({"seat_id": current_seat_id, "bid": bid})
    #修改当前座位的叫分存入到文件
    data["seats"][current_seat_id]["bid"]=bid 
    # 将JSON数据写入.json文件
    file_name = "round_bid_t_"+str(group_index)+"_"+str(banker)+"_"+str(current_seat_id)+".json"
    with open(file_name, "w") as json_file:
        json.dump(data, json_file, indent=4)

    for i in range(1,4):
        curr_index = (i+current_seat_id)%4
        pre_index = (curr_index-1)
        if(pre_index<0):
            pre_index = 3
        file_name = "round_bid_t_"+str(group_index)+"_"+str(banker)+"_"+str(pre_index)+".json"
        data = open(file_name).read()
        jsonData = json.loads(data)
        jsonData["current_seat_id"] = curr_index
        srn_py = ffi.new("rs_SpadesRound *", jsonData)
        stn_py = ffi.new("rs_SpadesTable *")
        # pprint(cdata_dict(srn_py))
        bid = lib.rs_SpadesAi_bid(srn_py, stn_py)
        print("seat_id = ",curr_index," bid = ",bid )
        bids.append({"seat_id": curr_index, "bid": bid})
        jsonData["seats"][curr_index]["bid"]=bid 
        # 将JSON数据写入.json文件
        file_name = "round_bid_t_"+str(group_index)+"_"+str(banker)+"_"+str(curr_index)+".json"
        with open(file_name, "w") as json_file:
            json.dump(jsonData, json_file, indent=4)
    # 按 seat_id 升序排序 data 数组
    # bids.sort(key=lambda x: x["seat_id"])
    for obj in bids:
        info = f"seat_id = {obj['seat_id']}, bid = {obj['bid']},cards = {cards_arr[obj['seat_id']]}"
        print(info)
        result.append(info)
    # 提取每个字典中的"seat_id"并按四个一列打印
    # for i, bid_info in enumerate(bids):
    #     print(f"{bid_info['bid']}")
    # 清理当前的文件
    result.append(("group index = "+str(group_index)+" end"))
# 检查文件是否存在并删除旧文件
if os.path.exists("spades_bid_result.txt"):
    os.remove("spades_bid_result.txt")
with open("spades_bid_result.txt", "w") as file:
    # 遍历数组中的每个元素，并将其写入文件中，每个元素占一行
    for line in result:
        file.write(line + "\n")

# 获取当前工作目录
current_directory = os.getcwd()

# 使用glob模块查找以"round_bid"开头的JSON文件
json_files = glob.glob("round_bid_t_*.json")

# 遍历找到的JSON文件并删除它们
for json_file in json_files:
    file_path = os.path.join(current_directory, json_file)
    try:
        os.remove(file_path)
    except OSError as e:
        print(f"Error deleting {json_file}: {e}")
